from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import ListModelMixin
from rest_framework.response import Response

from orders.models import OrderInfo
from orders.serializer import *

from goods.models import Good
from goods.serializer import GoodSer
# Create your views here.

# 订单的视图
class OrderInfoViewSet(ModelViewSet):
    queryset = OrderInfo.objects.all()
    serializer_class = OrderInfoSer
    lookup_url_kwarg = 'pk'
    lookup_field = 'pk'

    def retrieve(self, request, pk, *args, **kwargs):
        # 1.获取订单
        order = self.get_object()
        order_Ser = OrderInfoSer(order)

        # 2.获取订单商品
        order_goods = order.orderGoods.all()
        order_goods_ser = OrderGoodsSer(order_goods,many=True)

        # 3.修改订单商品的sku属性
        temp = []
        for i in order_goods_ser.data:
            i['sku'] = GoodSer(Good.objects.filter(id=i.get('sku')).first()).data

            # 存入一个临时列表
            temp.append(i)

        # 4.修改订单字典的skus
        order_dict = order_Ser.data
        order_dict['skus'] = temp

        return Response(order_dict)

    def update(self, request, *args, **kwargs):
        status = request.data.get('status')

        # 获取要更新的对象
        order = self.get_object()

        # 更新状态
        order.status = status
        order.save()

        print('>>>>>>>>>',status)
        return Response({'code':200,'msg':'更新订单状态成功'})


















